package carson.web.mvc;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 将二进制文件的内容发送到响应
 *
 * @author Carson Chen
 */
public class FileContentResult extends AbstractFileResult {

    /**
     * 实例化 FileContentResult
     *
     * @param fileContents     二进制文件的内容
     * @param contentType      内容类型
     * @param fileDownloadName 文件下载时的文件名
     */
    public FileContentResult(byte[] fileContents, String contentType, String fileDownloadName) {
        super(contentType);
        this.fileContents = fileContents;
        setFileDownloadName(fileDownloadName);
    }

    private byte[] fileContents;

    /**
     * 获取二进制文件的内容
     *
     * @return 二进制文件的内容 byte [ ]
     */
    public byte[] getFileContents() {
        return fileContents;
    }



    @Override
    protected void writeFile(HttpServletResponse response) throws IOException {
        ServletOutputStream out2 = null;
        try {
            response.setHeader("content-disposition", "attachment; filename="
                    + java.net.URLEncoder.encode(getFileDownloadName(), "UTF-8"));
            out2 = response.getOutputStream();
            out2.write(fileContents);
            out2.flush();
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            if (out2 != null)
                out2.close();
        }
    }
}
